package com.android.picotts.ui.activity.pick;

import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.picotts.R;
import com.android.picotts.ui.activity.common.TemplateActivity;
import com.android.picotts.ui.activity.pick.FileListAdapter.PFile;
import com.android.picotts.ui.widget.MyLetterListView;
import com.android.picotts.ui.widget.TitleBar;
import com.android.picotts.ui.widget.TitleBar.OnTitleClickListener;


public class PickFileActivity extends TemplateActivity implements OnItemClickListener{
    private static final String TAG = "HDExplorer";
    @SuppressLint("SimpleDateFormat")
    private SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd hh:mm"); 
    //the data source
    List<File> mbackwardfiles = null;
    List<File> mforwardfiles = null; 
    //BaseAdapter 
    FileListAdapter madapter = null; 
    //String
    private String mSDCardPath = null;
    private String mRootPath = null;
    //String
    private File mCurrentPathFile = null;
    private boolean misShowHiddenFiles = false; 
    //ListView
    ListView mListView = null;
    //TextView 
    TextView mEmptyView = null;
    TextView tx_path = null;
    
    private TextView overlay;
    private MyLetterListView letterListView;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.i(TAG,"onCreate");
        super.onCreate(savedInstanceState);
        initOverlay();
        setNoTitle();
        setContentView(R.layout.activity_pickfile);
        checkEnvironment();
        initUI();
        initData();
    }
    
    @Override
    protected void onDestroy() {
        WindowManager windowManager = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
        windowManager.removeView(overlay);
        super.onDestroy();
    }
    
    private void initOverlay() {
        LayoutInflater inflater = LayoutInflater.from(this);
        overlay = (TextView) inflater.inflate(R.layout.view_overlay_textview,null);
        overlay.setVisibility(View.INVISIBLE);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                PixelFormat.TRANSLUCENT);
        WindowManager windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        windowManager.addView(overlay, lp);
    }
    
    @Override
    protected void setupTitleBar(TitleBar titleBar) {
        titleBar.setTitle("选择文件");
        titleBar.setOnTitleClickListener(new OnTitleClickListener() {
            @Override
            public void onRightClick() {
                File f = madapter.getCheckFile();
                if(f != null) {
                    Intent data = new Intent();
                    data.setData(Uri.fromFile(f));
                    setResult(RESULT_OK, data);
                    finish();
                }else {
                    showToast("请先选择文件");
                }
            }
        }, false, true);
    }

    @Override
    public void setTitle(CharSequence title) {
        tx_path.setText(title);
    }
    
    private void initUI() {
        initMainUI();
    }

    private void initData() {
        File file = null;

        if(mCurrentPathFile != null){
            if(mCurrentPathFile.isDirectory()){
                file = mCurrentPathFile;
            }else{
                file = mCurrentPathFile.getParentFile();
            }
        }else{
            file = new File(mSDCardPath);
        }

        if(file != null){
            open(file,false);
        }
    }

    private void checkEnvironment() {
        File f = null; 
        boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if   (sdCardExist)   
        {                               
            f = Environment.getExternalStorageDirectory();
            if (f != null) {
                mSDCardPath = f.getAbsolutePath();
            }
            f = Environment.getRootDirectory();
            if (f != null) {
                mRootPath = f.getAbsolutePath();
            }
        }   else {
            mSDCardPath = "/";
            mRootPath = "/";
        }
    }
    
    public void onClick(View v) {
        switch(v.getId()) {
        case R.id.home:{
            File sdf = new File(mSDCardPath);
            open(sdf,false);
            mbackwardfiles.clear();
            mforwardfiles.clear();
            break;
        }
        case R.id.backward:{
            backward();
            break;
        }
        case R.id.upward:{
            upward();
            break;
        }
        case R.id.forward:{
            forward();
            break;
        }
        case R.id.refresh:{
            refresh();
            break;
        }
        }
    }

    public void initMainUI(){
        Log.i(TAG,"init");
        mEmptyView=(TextView)findViewById(R.id.empty);  
        mListView=(ListView)findViewById(R.id.listview);
        tx_path = getViewById(R.id.tx_path);
        
        mListView.setOnItemClickListener(this);
        mListView.setEmptyView(mEmptyView);
        
        mbackwardfiles = new ArrayList<File>();
        mforwardfiles = new ArrayList<File>();
        madapter = new FileListAdapter(this);
        mListView.setAdapter(madapter);
        
        letterListView =  getViewById(R.id.MyLetterListView);
        madapter.initAlpaIndex(overlay, mListView, letterListView);
        letterListView.setOnTouchingLetterChangedListener(madapter);
    }

    private void deleteAllItems()
    {
        Log.i(TAG,"deleteAllItems");
        madapter.removeAll();
    }
 
    private void open(File f ,boolean misAddToBackWardFiles){
        Log.i(TAG,"open");

        if(f == null)
            return;

        if(!f.exists())
            return;

        if(!f.canRead())
            return;

        if(f.isFile()){
            try {
                Intent intent = new Intent();
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setAction(Intent.ACTION_VIEW);
                String type = FileMimeTypes.getMIMEType(f);
                intent.setDataAndType(Uri.fromFile(f), type);
                startActivity(intent);
            } catch (ActivityNotFoundException e) {
                e.printStackTrace();
            }    

        }else if(f.isDirectory()){
            File[] files = f.listFiles();
            if(files == null) return;
            
            deleteAllItems();

            mCurrentPathFile = f;
            setTitle(mCurrentPathFile.getAbsolutePath());

            if (misAddToBackWardFiles) {
                mbackwardfiles.add(mCurrentPathFile.getParentFile());
            }
            List<PFile> fileList = new ArrayList<PFile>(files.length);
            for(File file:files){
                if(!misShowHiddenFiles && file.isHidden()){
                    continue;
                }
                fileList.add(new PFile(file));
            }
            if(fileList.size() >= 8) {
                Collections.sort(fileList, new Comparator<PFile>() {
                    @Override
                    public int compare(PFile f1, PFile f2) {
                        return f1.getPYName().toLowerCase().compareTo(f2.getPYName().toLowerCase());
                    }
                });
            }
            madapter.setList(fileList);
        }
    }
    
    private static long exitTime = 0;  
    public void upward(){
        if((mCurrentPathFile.getAbsolutePath()).equals(mSDCardPath))
        {
            if((System.currentTimeMillis()-exitTime) > 2000){  
                Toast.makeText(this, "再按一次返回！", Toast.LENGTH_SHORT).show();  
                exitTime = System.currentTimeMillis();  
            }else{
                setResult(RESULT_CANCELED);
                finish();
            }  
        }
        else{
            File f = mCurrentPathFile;
            if (!mCurrentPathFile.getAbsolutePath().equals(mRootPath)) {
                open(f.getParentFile(),true);
            }
        }
    }

    public void backward(){

        if (mbackwardfiles.size() > 0) {
            File backpathFile = mbackwardfiles.get(mbackwardfiles.size()-1);
            open(backpathFile, false);
            mforwardfiles.add(backpathFile);
            mbackwardfiles.remove(mbackwardfiles.size()-1);
        }
    }

    public void forward(){

        if (mforwardfiles.size() > 0) {
            File forwardpathFile = mforwardfiles.get(mforwardfiles.size()-1);
            open(forwardpathFile, true);
            mbackwardfiles.add(forwardpathFile);
            mforwardfiles.remove(mforwardfiles.size()-1);
        }
    }
    
    public void refresh(){
        if (mCurrentPathFile != null) {
            open(mCurrentPathFile,false);
        }
    }

    public boolean checkFileExist(File f){
        boolean ret = false;

        File[] files = mCurrentPathFile.listFiles();
        if(files == null) return false;
        
        for(File file:files){
            if((f.getName()).equals(file.getName())){
                ret = true;
                break;
            }
        }

        return ret;
    }

    public String combineFilename(File src,File dest){
        String destname = null;

        if (src == null || dest == null || !dest.isDirectory()) {
            return destname;
        }

        destname = dest.getAbsolutePath()+"/"+src.getName();

        return destname;
    }
    
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        Log.i(TAG,"onActivityResult");

        try {
            super.onConfigurationChanged(newConfig);
            if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            }
        } catch (Exception e) {
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.i(TAG,"onKeyDown");
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                upward();
                return true;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        File mselectedFile = madapter.getItem(position).file;
        if(mselectedFile != null)
            open(mselectedFile,true);
    }

    public String getFileTime(long filetime) {
       
        String ftime =  formatter.format(new Date(filetime)); 
        return ftime;
    }

    public String getFileSize(long filesize) {
        DecimalFormat df = new DecimalFormat("#.00");
        StringBuffer mstrbuf = new StringBuffer();

        if (filesize < 1024) {
            mstrbuf.append(filesize);
            mstrbuf.append(" B");
        } else if (filesize < 1048576) {
            mstrbuf.append(df.format((double)filesize / 1024));
            mstrbuf.append(" K");           
        } else if (filesize < 1073741824) {
            mstrbuf.append(df.format((double)filesize / 1048576));
            mstrbuf.append(" M");           
        } else {
            mstrbuf.append(df.format((double)filesize / 1073741824));
            mstrbuf.append(" G");
        }

        df = null;

        return mstrbuf.toString();
    }

    public static void startActivityForResult(Activity activity, int reqCode) {
        Intent it  = new Intent(activity, PickFileActivity.class);
        activity.startActivityForResult(it, reqCode);
    }
}